<template>
  <div class='detail-wrap'>
    <loading :show='showLoading'/>
    <div class='detail-cover'>
      <div class='play' @click='playHandler(detail.url)'></div>
      <canvas id='c'></canvas>
    </div>
    <div class='detail'>
      <h3>{{ detail.name }}</h3>
      <div class='desc'>
        {{ detail.intro }}
      </div>
    </div>
  </div>
</template>
<script>
import * as THREE from 'three';
import { DeviceOrientationControls } from 'three/examples/jsm/controls/DeviceOrientationControls';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import Loading from './Loading.vue';
import list from '../config';

export default {
  components: {
    Loading
  },
  data() {
    return {
      showLoading: true,
      detail: {}
    };
  },
  created() {
    const {
      id,
      type
    } = this.$route.query;
    const arr = list[type];
    // eslint-disable-next-line no-restricted-syntax
    for (const item of arr) {
      if (item.id === id) {
        this.detail = { ...item };
      }
    }
  },
  methods: {
    playHandler(url) {
      window.location.href = url;
    }
  },
  mounted() {
    const isIos = /iPad|iPhone|iPod/.test(navigator.userAgent);
    const self = this;
    const c = document.querySelector('#c');
    const w = window.innerWidth;
    const h = 500;
    const renderer = new THREE.WebGLRenderer({
      canvas: c,
      antialias: true
    });
    renderer.setSize(w, h);
    renderer.setPixelRatio(window.devicePixelRatio);
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(60, w / h, 0.01, 1000);
    camera.position.set(-20, 0, 2);
    let control = null;
    if (!isIos) {
      control = new DeviceOrientationControls(camera);
    } else {
      control = new OrbitControls(camera, renderer.domElement);
      control.autoRotate = true;
      control.autoRotateSpeed = 1.0;
    }
    const sphereGeo = new THREE.SphereBufferGeometry(200, 200, 200);
    sphereGeo.scale(-1, 1, 1);

    new THREE.TextureLoader().load(self.detail.cover, (texture) => {
      texture.wrapS = THREE.RepeatWrapping;
      texture.wrapT = THREE.RepeatWrapping;
      const sphereMat = new THREE.MeshBasicMaterial({
        map: texture,
        side: THREE.DoubleSide
      });
      const sphere = new THREE.Mesh(sphereGeo, sphereMat);
      scene.add(sphere);
      self.showLoading = false;
    });

    const render = () => {
      renderer.render(scene, camera);
      control.update();
      requestAnimationFrame(render);
    };
    render();
  }
};
</script>
